package tree;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class findMode {
    Map<Integer, Integer> map;
    TreeNode pre = null;
    public int[] findMode(TreeNode root) {
        map = new HashMap<>();
        if (root == null){
            return new int[]{0};
        }
        preorder(root);
        int maxCount = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()){
            if (entry.getValue() > maxCount){
                maxCount = entry.getValue();
            }
        }
        List<Integer> result = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == maxCount){
                result.add(entry.getKey());
            }
        }
        return result.stream()
                .mapToInt(Integer::intValue)
                .toArray();
    }
    public void preorder(TreeNode root){
        if (root == null){
            return;
        }
        map.put(root.val, map.getOrDefault(root.val, 0) + 1);
        preorder(root.left);
        preorder(root.right);
    }
}
